package day0728API;

import java.io.*;
import java.net.Socket;

public class S1_T extends  Thread{

    Socket  s=null;
    String ip;
    S1_T(Socket  s){
        this.s=s;
        //Socket s.getInetAddress();获取一个表示电脑网络地址的InetAddress兑现
        //InetAddress 的成员方法getHostAddress（）表示获取ip的String形式
        ip=s.getInetAddress().getHostAddress();
    }

    public void run() {
        PrintWriter pw=null;
        try{
            InputStream is=s.getInputStream();
            InputStreamReader isr=new InputStreamReader(is);
            BufferedReader br=new BufferedReader(isr);

            OutputStream os=s.getOutputStream();
            OutputStreamWriter osw=new OutputStreamWriter(os);
            pw=new PrintWriter(osw);
            synchronized (S1.class){
                S1.allPrintWriter.add(pw);
            }

            sendMsg("客户端"+ip+"上线了，目前在线人数为:"+ S1.allPrintWriter.size());

            while(true){
                String clientMsg=br.readLine();
                System.out.println(clientMsg);
                sendMsg(ip+"说 ："+clientMsg);
            }
        }catch (IOException e){
            //e.printStackTrace();
        }finally {//添加了finally来从集合中删除下线的客户端对应的输出流，
            // 为了remove中能传递被删除的输出流： 将输出流的封装及存入到集合的代码剪切到S1_T线程中的run方法中了
            synchronized (S1.class){
                S1.allPrintWriter.remove(pw);
            }
            sendMsg(ip+"客户端下线了,当前聊天室的在线人数为："+S1.allPrintWriter.size());
        }
    }



    private void sendMsg(String clientMsg) {
        for(PrintWriter pw  :  S1.allPrintWriter){
            pw.println(clientMsg);
            pw.flush();
        }
    }

}
